<?php

/**
 * Main application entry point
 *
 */
class Users_Controller extends SPF_Controller {

   /**
    * The version number of the controller.
    * @var     string
    */
   const VERSION = '1.0.0';

   /**
    * The author of the controller.
    * @var     string
    */
   const AUTHOR  = 'Simon Downes';

   /**
    * Constructor
    * @return       void
    */
   public function __construct() {
      /* construct the parent object */
      parent::__construct(__CLASS__);
   }

   /**
    * Destructor
    * @return       void
    */
   public function __destruct() {
      parent::__destruct();
   }

   /**
    * Determines if the current user is permitted to access this controller and perform the requested action
    * @return       boolean   true if access is allowed, false otherwise.
    */
   public function authenticate() {
   
      switch( SPF::$route['action'] ) {
         case 'signin':
         case 'signout':
         case 'register':
         case 'activate':
            return true;
         default:
            return (SPF::$session->user != NULL);
      }
      
   } // authenticate
   
   /**
    * Creates an authenticated user session.
    */
   public function signin() {
      
      SPF::$session->user = NULL;;
      
      if( SPF::form_submitted('frm_signin') ) {
         
         $user_name = SPF::post('user_name');
         $password  = SPF::hash(SPF::post('password'));
         
         $user_status = User::signin($user_name, $password);
         
         switch( $user_status ) {
            
            // invalid username/password
            case NULL:
            case 'DELETED':
               $this->assign('invalid', true);
               $this->assign('user_name', $user_name);
               break;
            
            // user has not yet been activated so we should tell them that...
            case 'NOT_ACTIVATED':
               $this->assign('not_activated', true);
               $this->assign('user_name', $user_name);
               break;
               
            case 'ACTIVE':
               $user = new User();
               $user->fetch($user_name);
               SPF::$session->user = $user->to_array();
               SPF::redirect();
               break;
         
         } // switch $user_status
         
      }
      
      $this->display('signin');
      
   } // signin
   
   /**
    * Destroys an authenticated user session.
    */
   public function signout() {
      
      SPF::$session->destroy();
      
      SPF::redirect('users', 'signin');
      
   } // signout
   
   /**
    * Allows a new user to register with the application.
    */
   public function register() {
      
      // if registration is disabled and there is no current user then redirect to homepage
      if( !(int) SPF::$registry->get('users.allow_registration') && !SPF::$session->user )
         SPF::redirect();
      
      if( SPF::form_submitted('frm_register') ) {

         // load the request lookup object
         $user = new User();
         
         // don't use from_array() as people could post extra data in the request,
         // and we don't want people activating their accounts and setting groups, etc...
         $user->user_name    = SPF::post('user_name');
         $user->display_name = SPF::post('display_name');
         $user->email        = SPF::post('email');
         $user->password     = SPF::post('new_password');
         $user->confirm_pw   = SPF::post('confirm_pw');
         
         $user->validate();
         
         // check if user already exists
         if( $user->exists(SPF::post('user_name')) ) {
            $user->set_error('user_name', 'User already exists.');
         }
         
         // everything is ok...
         if( !$user->has_errors() ) {
               
            // update the user record
            $user->update(false);
            
            // send activation email..
            $email = new SPF_Email();
            
            $email->sender = SPF::$registry->get('mail.from', 'sitrack@localhost');
            $email->subject = 'New SiTrack Account';
            $email->add_recipient($user->email);
            
            // allow the user to activate their account if either new users are allowed to or an existing user is creating a new user
            $auto_activate = (int) SPF::$registry->get('users.auto_activation') || SPF::$session->user;
            
            $template = SPF_Template::factory('smarty');
            $template->assign('user_name', $user->user_name);
            $template->assign('password', SPF::post('password'));
            $template->assign('auto_activate', $auto_activate);
            $template->assign('activate_link', SPF::get_base_url('users', 'activate', array($user->user_name, $user->password)));
            
            $email->body = $template->fetch('users/email_welcome');
               
            $email->send();
            
            $this->assign('completed', true);
            
         }

         $this->assign('user', $user->to_array());

      } // is_submitted

      $this->display('register');

   } // register
   
   /**
    * Activates a new user.
    */
   public function activate( $user_name = NULL, $password = NULL) {
      
      if( !$user_name || !$password )
         $success = false;
      else
         $success = User::activate($user_name, $password);
      
      $user = new User();
      $user->fetch( $user_name );
      
      // if successful and there is a current user then
      // email the new user to tell them their account is active and then return to the user list
      if( $success && SPF::$session->user ) {
         
         // send activation email..
         $email = new SPF_Email();
         
         $email->sender = SPF::$registry->get('mail.from', 'sitrack@localhost');
         $email->subject = 'SiTrack Account Activated';
         $email->add_recipient($user->email);
         
         $template = SPF_Template::factory('smarty');
         $template->assign('name', $user->display_name);
         $template->assign('signin_link', SPF::get_base_url('users', 'signin'));
         
         $email->body = $template->fetch('users/email_activated');
            
         $email->send();
         
         SPF::redirect('users', 'index');
         
      } // activated by existing user
      
      $this->assign('success', $success);
      $this->assign('user', $user->to_array());
      
      $this->display('activated');
      
   } // activate
   
   /**
    * Allows a user to edit their personal information and change their password.
    */
   public function myinfo() {
      
      // fetch the current users data
      $user = new User();
      $user->fetch(SPF::$session->user['user_name']);
      
      if( SPF::form_submitted('frm_my_info') ) {

         // don't use from_array() as people could post extra data in the request,
         // and we don't want people activating their accounts and setting groups, etc...
         $user->display_name = SPF::post('display_name');
         $user->email        = SPF::post('email');
         
         if( SPF::post('new_password') ) {
            $user->password     = SPF::post('new_password');
            $user->confirm_pw   = SPF::post('confirm_pw');
         }
         
         $user->validate();
         
         // everything is ok...
         if( !$user->has_errors() ) {
               
            // update the user record
            $user->update(false);
            
            SPF::flash(SiTrack::MSG_SAVED, 'success');
            
            // redirect to dashboard
            SPF::redirect();
            
         }

         SPF::flash(SiTrack::MSG_ERRORS, 'error');
         
      } // is_submitted

      $this->assign('user', $user->to_array());

      $this->display('my_info');

   } // myinfo
   
   /**
    * Lists the users.
    */
   public function index() {
      
      $this->assign('users', User::browse_data());
      
      $this->display('browse');
      
   } // index
   
   /**
    * Edit a user record. Doesn't allow changing of a users password.
    */
   public function edit( $user_name = NULL ) {
      
      // fetch the users data
      $user = new User();
      if( !$user->fetch($user_name) )
         throw new SPF_Exception('User Not Found: '. $user_name);
      
      if( SPF::form_submitted('frm_user') ) {

         // don't use from_array() as people could post extra data in the request,
         // and we don't want people activating their accounts and setting groups, etc...
         $user->display_name = SPF::post('display_name');
         $user->email        = SPF::post('email');
         
         $user->validate();
         
         // everything is ok...
         if( !$user->has_errors() ) {
               
            // update the user record
            $user->update(false);
            
            SPF::flash(SiTrack::MSG_SAVED, 'success');
            
            // redirect to dashboard
            SPF::redirect('users', 'index');
            
         }

         SPF::flash(SiTrack::MSG_ERRORS, 'error');
         
      } // is_submitted

      $this->assign('user', $user->to_array());

      $this->display('edit');

   } // edit
   
   /**
    * Deletes a user from the application.
    * User's details are removed from the user record and the status set to deleted.
    * Comments and tickets created by the user are not deleted and still point to the user record.        
    */
   public function delete( $user_name ) {
      
      
      $this->display();
      
   } // delete
   
} // Users_Controller

?>
